/* EasyWay Game Engine
 * Copyright (C) 2006 Daniele Paggi.
 *  
 * Written by: 2006 Daniele Paggi<dshnt@hotmail.com>
 *   
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 * 
 * You should have received a copy of the GNU Library General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
package org.easyway.objects;

import java.lang.reflect.Method;
import org.easyway.interfaces.extended.ILoopable;
import org.easyway.utils.Utility;

/**
 *
 * @author Daniele Paggi
 */
public class EventCaller extends BaseObject implements ILoopable {

    /**
     * the number of signal input
     */
    int inputNumber;
    /**
     * the number of recived signal input
     */
    int recivedInputNumber;
    Object target;
    Method targetMethod;
    static Object[] defaultParams = {};

    public EventCaller(Object target, String methodName, int inputNumber) {
        this.target = target;
        this.inputNumber = inputNumber;
        try {
            targetMethod = target.getClass().getDeclaredMethod(methodName, new Class[]{});
        } catch (NoSuchMethodException ex) {
            Utility.error("method: " + methodName + " in class: " + target.getClass().getCanonicalName() + " not found!", ex);
        }
    }

    protected EventCaller(Object target, int inputNumber) {
        this.target = target;
        this.inputNumber = inputNumber;
    }

    public void loop() {
        recivedInputNumber = 0;
    }

    public void callEvent() {
        if (targetMethod != null && target != null) {
            try {
                targetMethod.invoke(target, defaultParams);
            } catch (Exception ex) {
                Utility.error("error calling the event", ex);
            }
        }
    }

    public void signal() {
        ++recivedInputNumber;

        // Using recivedInputNumber == inputNumber and not:
        // recivedInputNumber >= inputNumber
        // we'll gain that the callEvent will be called only 1 time for each 
        // loop data game
        if (recivedInputNumber == inputNumber) {
            callEvent();
        }
    }

    public int getRecivedInputNumber() {
        return recivedInputNumber;
    }

    public int getInputNumber() {
        return inputNumber;
    }

    public void setInputNumber(int inputNumber) {
        this.inputNumber = inputNumber;
    }
}
